package com.mcf.xiaolinju.interceptor;

import com.mcf.xiaolinju.token.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor extends HandlerInterceptorAdapter {
    @Override


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("interceptor:"+request.getRequestURI());
        //放行OPTIONS请求
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }
        String authHeader = request.getHeader("Authorization");
        System.out.println(authHeader);
        if (authHeader == null || !authHeader.startsWith("Bearer:")) {
            throw new UserLoginException("用户未登录");
        }

//取得token
        String token = authHeader.substring(7);

//验证token
        Claims claims = JwtUtil.checkToken(token);

        request.setAttribute("username", claims.getSubject());

        return true;

    }
}
